var bcrypt = dcodeIO.bcrypt; //use the bcrypt library
function signup() {
    const name = document.getElementById('newname').value;
const email = document.getElementById('newemail').value;
const password1 = document.getElementById('newpassword1').value;
const password2 = document.getElementById('newpassword2').value;

if (password1 === password2) {
    //Do something
    } else {
    alert('Passwords do not match!');
    }
    // create a random salt value
// encrypt the password with the salt
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password1, salt);
users.push({ name, email, password: hashedPassword, count:0 });
users.push({ name, email, password: hashedPassword, count:0, history: []});
// read the current users array
// push this user into the users array
users = JSON.parse(localStorage.getItem("users"));
if (users === null) //if there are no users yet
users = []; //initialize it to empty
users.push({ name, email, password: hashedPassword });
alert('User registered with hashed password. Welcome ' + name);
// save the newly updated users JSON to "database"
// redirect User back to Log In page
localStorage.setItem("users", JSON.stringify(users));
window.location.href = "./login.html";
}    

function login() {
    // read the "database" of users from local storage
    const storedUsers = localStorage.getItem("users");
    const users = storedUsers ? JSON.parse(storedUsers) : [];

    // read the login email and password
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    // get one user if the emails match
    const user = users.find(u => u.email === email);

    // if exists, and the password matches
    // then successful login.
    // save this "loggedinUser" into local storage
    if (user && bcrypt.compareSync(password, user.password)) {
        alert('Login successful! for ' + user.name);
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        window.location.href = "./main.html";
    } else {
        alert('Login failed.');
    }
}

